# coding:utf-8
import cv2
import time

w = 640
h = 480
left_camera = cv2.VideoCapture(0)
left_camera.set(cv2.CAP_PROP_FRAME_WIDTH, w)
left_camera.set(cv2.CAP_PROP_FRAME_HEIGHT, h)


AUTO = False  # True自动拍照，False则手动按s键拍照
INTERVAL = 0.0000005  # 调整自动拍照间隔

cv2.namedWindow("left")
cv2.moveWindow("left", 0, 0)
cv2.resizeWindow("left",w+10,10)

counter = 0
utc = time.time()
folder = "./image/left"  # 照片存储路径

# shot保存图像
def shot(pos, frame):
    global counter                                   # 全局变量，计数
    # timestr = datetime.datetime.now()
    path = folder+"/" + pos + "_" + str(counter) + ".jpg"
    cv2.imwrite(path, frame)
    print("snapshot saved into: " + path)
while (1):
    ret, left_frame = left_camera.read()
    if(ret == 0):
        break
    left_frame = cv2.resize(left_frame,(w,h))
    cv2.imshow("left", left_frame)
    now = time.time()

    # 自动保存
    if AUTO and now - utc >= INTERVAL:
        shot("left", left_frame)
        # shot("right", right_frame)
        counter += 1
        utc = now
    # 手动保存
    key = cv2.waitKey(1)
    if key == ord("q"):                            # 安q停止
        break
    elif key == ord("s"):                           # 安s保存
        shot("left", left_frame)                     # 保存左相机
        counter += 1                                # 计数

left_camera.release()
cv2.destroyWindow("left")
